package com.clob.dbtools;

import com.clob.properties.SingleTonLoadProperties;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 */
public class JDBCTools {

    private static ComboPooledDataSource dataSource;

    static {
        initDataSourse();
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void release(Connection connection,Statement statement){
        release(connection, statement,null);
    }

    public static void release(Connection connection){
        release(connection, null, null);
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始化datasource
     */
    private static void initDataSourse(){
        SingleTonLoadProperties singleTonLoadProperties = SingleTonLoadProperties.getInstance("jdbc.properties");
        dataSource = new ComboPooledDataSource();

        dataSource.setUser(singleTonLoadProperties.getProperty("orcl.username"));
        dataSource.setPassword(singleTonLoadProperties.getProperty("orcl.password"));
        dataSource.setJdbcUrl(singleTonLoadProperties.getProperty("orcl.url"));
        try {
            dataSource.setDriverClass(singleTonLoadProperties.getProperty("orcl.driver"));
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

}
